<?php

namespace App\Http\Middleware;

use App\Common\Constant\Params;
use App\Common\Constant\Status;
use App\Services\ICookieService;
use Closure;
use View;
use App\Services\IWeixinService;
use App\Services\ISessionService;

/**
 * 微信授权自动登录
 * @package App\Http\Middleware
 */
class WeixinAuth
{
    
    private $sessionService;
    private $cookieService;
    
    public function __construct(ISessionService $sessionService, ICookieService $cookieService)
    {
        $this->sessionService = $sessionService;
        $this->cookieService = $cookieService;
    }
    
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        /**
         * 检查平台用户
         */
        $user = $this->sessionService->getCurrentUser();
        if (empty($user)){
            return redirect(route('autoLogin',['redirectUrl'=>url()->full()]));
        }
        $userid = $this->cookieService->currentUserid();
        if (empty($userid)){
            return redirect(route('autoLogin',['redirectUrl'=>url()->full()]));
        }

        /**
         * 检查用户是否正在审核中
         */
        if ($user->status == Params::USER_STATUS_REVIEW){
//            return redirect(route('503'))->with('errorCode', Status::USER_BEING_REVIEW);
//            return response(status(Status::USER_BEING_REVIEW));
            return response(view('auth/registerSuccess'));
        }

        /**
         * 检查用户是否正在停单中
         */
        if ($user->status == Params::USER_STATUS_STOP){
//            return redirect(route('503'))->with('errorCode', Status::USER_BEING_STOP);
            if (empty($user->disable_time)){
                return response('抱歉，您的账号已永久停单。');
            }else{
                $rest_time = $user->disable_time->timestamp - time();
                $text = '';
                $days = intval($rest_time/86400);
                if ($days){
                    $text .= "{$days}天";
                    $rest_time -= 86400*$days;
                }
                $hours = intval($rest_time/3600);
                if ($hours){
                    $text .= "{$hours}小时";
                    $rest_time -= 3600*$hours;
                }
                $minutes = intval($rest_time/60);
                if ($minutes){
                    $text .= "{$minutes}分";
                }else if (empty($text)){
                    $text = '1分钟';
                }
                return response("抱歉，您还在处罚期，暂不能报价接单，请在{$text}后再进行报价接单。");
            }

        }
        
        return $next($request);
    }
}
